<template>
    <section>
        <el-table header-cell-class-name="text-black" row-key="id" :data="state.data" border height="calc(100vh - 120px)"
            style="width: 99%" :tree-props="{ children: 'data' }" @row-dblclick="showEditPutStock">
            <el-table-column prop="pIp" label="IP" />
            <el-table-column align="center" prop="name" label="商品">
                <template #default="scope">
                    <p v-if="scope.row.name" class="text-center">
                        {{ scope.row.name }}
                    </p>
                    <p v-else></p>
                    <div class=" absolute right-[10px] top-[7px]">
                        <el-button v-if="scope.row.name" type="danger" size="small" circle
                            @click="removeStockRecord(scope.row)">
                            <el-icon><i-ep-Delete /></el-icon>
                        </el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="price" label="单价" width="100">
                <template #default="scope">
                    <p v-if="scope.row.price" class="text-center text-[#ff4d4d]">
                        {{ scope.row.price }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="orders" label="订单数" width="100" />
            <el-table-column align="center" prop="total" label="出货数" width="120" />
            <el-table-column align="center" prop="postage" label="邮费" width="120">
                <template #default="scope">
                    <p v-if="scope.row.postage" class="text-center text-blue">
                        {{ scope.row.postage }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
            <el-table-column sortable align="center" prop="sum" label="总价" width="120">
                <template #default="scope">
                    <p v-if="scope.row.sum" class="text-center text-[#ff4d4d] font-bold">
                        {{ scope.row.sum }}￥
                    </p>
                    <p v-else></p>
                </template>
            </el-table-column>
        </el-table>

        <el-row class="my-[10px] mr-[20px]" justify="end">
            <el-col>
                <ul class="flex flex-1 justify-end items-center font-bold">
                    <p class="mx-[10px]">出货订单数：<span class="text-[#ff4d4d]">
                            {{ (state.totalObj?.orders || 0) + ' ' }}</span>单
                    </p>
                    <p class="mx-[10px]">出货总数：<span class="text-[#ff4d4d]">
                            {{ (state.totalObj?.total || 0) + ' ' }}</span>件
                    </p>
                    <p class="mx-[10px]">出货总邮费：<span class="text-[#ff4d4d]">
                            {{ state.totalObj?.postage || 0 }}￥</span>
                    </p>
                    <p class="mx-[10px]">出货总额：<span class="text-[#ff4d4d]">
                            {{ state.totalObj?.sum || 0 }}￥</span>
                    </p>
                    <el-button type="primary" @click="loadData(true)">
                        <el-icon><i-ep-Refresh /></el-icon>&nbsp;刷新
                    </el-button>
                </ul>
            </el-col>
        </el-row>

        <operate-stock v-if="state.showStock" v-model="state.showStock" v-model:pageType="state.pageType"
            v-model:currentProduct="state.currentProduct" :currentStock="state.currentStock" :refresh="loadData" />
    </section>
</template>

<script lang='ts' setup>
import { Product, Stock } from '@/components/product/type';
import Decimal from 'decimal.js';
import { dayjs } from "element-plus";

type StockProduct = Stock & Product & { orders: string }

type Count = {
    orders: number,
    sum: number,
    total: number,
    postage: number,
}

type OutRecord = {
    id?: string,
    pIp?: string,
    name?: string,
    price: number | string,
    data?: OutRecord[]
} & Count

type Props = {
    data: OutRecord[],
    totalObj: Count | null,
    showStock: boolean,
    pageType: number,
    currentProduct: Product,
    currentStock: StockProduct,
}
const state = reactive<Props>({
    data: [],
    totalObj: null,

    showStock: false,
    pageType: 1,
    currentProduct: {} as Product,
    currentStock: {} as StockProduct,
})

const buildMap = (map: Map<string, OutRecord>, _: StockProduct) => {
    let current = map.get(_.pIp)
    if (!current) {
        current = {
            id: Utils.guid(),
            pIp: _.pIp,
            orders: 1,
            price: '',
            total: parseInt(_.total),
            postage: new Decimal(_.postage).toNumber(),
            sum: new Decimal(_.sum).toNumber(),
            data: [_ as any]
        }
        return map.set(_.pIp, current)
    }
    current.orders += 1
    current.total += parseInt(_.total)
    current.postage = new Decimal(_.postage).add(current.postage).toNumber()
    current.sum = new Decimal(_.sum).add(current.sum).toNumber()
    current.data?.push(_ as any)
    map.set(_.pIp, current)
}

const buildData = (data: OutRecord[] | undefined) => {
    const _map = new Map<string, OutRecord>()
    data?.forEach((_: any) => {
        let current = _map.get(_.name)
        const name = _.name
        _.orders = 1
        if (!current) {
            current = {
                id: Utils.guid(),
                pIp: _.pIp,
                name: name,
                orders: 1,
                price: '',
                total: parseInt(_.total),
                postage: new Decimal(_.postage).toNumber(),
                sum: new Decimal(_.sum).toNumber(),
                data: [_ as any]
            }
            return _map.set(name, current)
        }
        current.orders += 1
        current.total += parseInt(_.total)
        current.postage = new Decimal(_.postage).add(current.postage).toNumber()
        current.sum = new Decimal(_.sum).add(current.sum).toNumber()
        current.data?.push(_)

        return _map.set(name, current)
    })
    data = [..._map.values()]
}

const loadData = async (showLoading?: boolean) => {
    showLoading && Utils.Modal().loading('加载中~')
    const [err, res] = await ProductService.stockHomeProductOut()
    showLoading && Utils.Modal().closeLoading()

    if (err) return Utils.Modal().msgError(err)
    const { data = [] } = res || {}
    const map = new Map<string, OutRecord>()

    const temp = {
        orders: 0,
        total: 0,
        sum: 0,
        postage: 0,
    }

    data.forEach((_: StockProduct) => {
        temp.total = new Decimal(temp.total).add(_.total).toNumber()
        temp.sum = new Decimal(temp.sum).add(_.sum).toNumber()
        temp.postage = new Decimal(temp.postage).add(_.postage).toNumber()

        buildMap(map, _)
    });
    temp.orders = data.length
    const result = [...map.values()]
    result.forEach((item: OutRecord) => buildData(item.data))

    state.data = result
    state.totalObj = temp
}

const showEditPutStock = async (item: StockProduct) => {
    if (!item.pId) return
    const [productErr, product] = await ProductService.getProductById({ pId: item.pId })
    if (productErr) return Utils.Modal().msgError(productErr)
    state.currentProduct = product.data
    state.currentStock = item
    state.showStock = true
}

const removeStockRecord = async (row: StockProduct) => {
    const { guid, pIp, name } = row
    const [err, res] = await Utils.Modal().confirm(`确定需要删除记录 “${pIp}-${name}” 吗？`);
    if (err) return;
    const [delErr, del] = await ProductService.removeStockRecord(guid);
    if (delErr) {
        return Utils.Modal().msgError(delErr);
    }
    Utils.Modal().msgSuccess("删除成功~");
    loadData()
}

loadData()
</script>

<style lang='scss' scoped></style>